﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class TrainingForm : Form
    {
        bool IsRep, insert = true;

        public TrainingForm(bool rep)
        {
            this.IsRep = rep;
            InitializeComponent();
        }

        int regID;
        tb_training training;

        private void TrainingForm_Load(object sender, EventArgs e)
        {
            //cbAudience.Items.AddRange(UtilClass.GetCategory("Audience"));
            //cbAudience.SelectedIndex = -1;

            if (IsRep)
            {
                tabControl1.SelectedTab = tabPageViewTraining;
                tsbDelete.Visible = tsbEdit.Visible = false;
                tsbReport.Visible = true;
                butPrint.Visible = true;
            }
            else
            {
                tsbDelete.Visible = tsbEdit.Visible = true;
                tsbReport.Visible = false;
                butPrint.Visible = false;
            }

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
                cbRegion.DataSource = UtilClass.FillCBRegions();
                cbRegion.DisplayMember = "Name";
                cbRegion.ValueMember = "ID";
                cbRegion.SelectedIndex = -1;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);

                cbTrRegion.SelectedIndexChanged -= cbTrRegion_SelectedIndexChanged;
                cbTrRegion.DataSource = UtilClass.FillCBRegions();
                cbTrRegion.DisplayMember = "Name";
                cbTrRegion.ValueMember = "ID";
                cbTrRegion.SelectedIndex = -1;
                cbTrRegion.SelectedIndexChanged += new EventHandler(cbTrRegion_SelectedIndexChanged);

            }
            else
            {
                regID = InformationClass.regionID;
                cbRegion.Enabled = cbTrRegion.Enabled = false;
            }
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                regID = Convert.ToInt32(cbRegion.SelectedValue);
            }
        }

        private void cbTrRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbTrRegion.SelectedIndex >= 0)
            {
                regID = Convert.ToInt32(cbTrRegion.SelectedValue);
            }
        }


        private void buttonTrOK_Click(object sender, EventArgs e)
        {
            if (regID < 0 ||
                String.IsNullOrEmpty(tbTrainingName.Text) ||
                String.IsNullOrEmpty(tbPlace.Text) ||
                String.IsNullOrEmpty(tbResponsiblePerson.Text))
            {
                if (InformationClass.Lang)
                    MessageBox.Show("Заполнены не все ключевые параметры.");
                else
                    MessageBox.Show("Асосий параметрларнинг барчаси тўлдирилмаган.");
                return;
            }
            if (insert)
            {
                training = new tb_training
                {
                    Activity = tbActivity.Text,
                    RegionID = regID,
                    BUIS = (int)nudBUIS.Value,
                    DayCount = (int)nudDayCount.Value,
                    Men = (int)nudMan.Value,
                    Name = tbTrainingName.Text,
                    Objective = tbObjective.Text,
                    Participant = (int)nudParticipant.Value,
                    Place = tbPlace.Text,
                    ResponsiblePerson = tbResponsiblePerson.Text,
                    Date = dtpDate.Value.Date,
                    UIS = (int)nudUIS.Value,
                    Women = (int)nudWoman.Value,
                    Audience = tbAudience.Text
                };
                //if (cbAudience.SelectedIndex >= 0)
                //    training.Audience = UtilClass.GetCategoryValue("Audience", cbAudience.Items[cbAudience.SelectedIndex].ToString());
                //else
                //    training.Audience = 0;

                DBClass.Trainings.InsertOnSubmit(training);
            }
            else
            {
                if (training != null)
                {
                    training.Activity = tbActivity.Text;
                    training.RegionID = regID;
                    training.BUIS = (int)nudBUIS.Value;
                    training.DayCount = (int)nudDayCount.Value;
                    training.Men = (int)nudMan.Value;
                    training.Name = tbTrainingName.Text;
                    training.Objective = tbObjective.Text;
                    training.Participant = (int)nudParticipant.Value;
                    training.Place = tbPlace.Text;
                    training.ResponsiblePerson = tbResponsiblePerson.Text;
                    training.Date = dtpDate.Value.Date;
                    training.UIS = (int)nudUIS.Value;
                    training.Women = (int)nudWoman.Value;
                    training.Audience = tbAudience.Text;
                    //if (cbAudience.SelectedIndex >= 0)
                    //    training.Audience = UtilClass.GetCategoryValue("Audience", cbAudience.Items[cbAudience.SelectedIndex].ToString());
                    //else
                    //    training.Audience = 0;


                }

                insert = true;
                buttonTrOK.Text = "Добавить";
            }
            try
            {
                DBClass.RESPContext.SubmitChanges();
                MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                tbActivity.Text = tbAudience.Text = tbObjective.Text = tbPlace.Text = tbResponsiblePerson.Text =
                tbTrainingName.Text = string.Empty;
                nudBUIS.Value = nudDayCount.Value = nudMan.Value = nudParticipant.Value = nudUIS.Value =
                    nudWoman.Value = 0;
                dtpDate.Value = DateTime.Now.Date;
            }
            catch (Exception ex)
            {
                MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                DBClass.Trainings.DeleteOnSubmit(training);
                DBClass.RESPContext.SubmitChanges();
            }


        }

        private void tsbEdit_Click(object sender, EventArgs e)
        {
            if (dgvTrainings.RowCount > 0 && dgvTrainings.CurrentRow != null)
            {
                insert = false;
                buttonTrOK.Text = "Изменить";

                if (cbTrRegion.SelectedIndex < 0)
                {
                    if (InformationClass.Lang)
                        MessageBox.Show("Укажите Район");
                    else
                        MessageBox.Show("Туман белгиланг");
                    return;
                }

                DateTime trDate = (DateTime)dgvTrainings["TrDate", dgvTrainings.CurrentRow.Index].Value;
                training = DBClass.Trainings.Where(wh => wh.Date == trDate && wh.RegionID == regID).SingleOrDefault();

                if (training != null)
                {
                    if (InformationClass.isAdmin)
                        cbRegion.SelectedIndex = cbTrRegion.SelectedIndex;

                    tbActivity.Text = training.Activity;
                    tbObjective.Text = training.Objective;
                    tbPlace.Text = training.Place;
                    tbResponsiblePerson.Text = training.ResponsiblePerson;
                    tbTrainingName.Text = training.Name;
                    tbAudience.Text = training.Audience;
                    nudDayCount.Value = (int)training.DayCount;
                    nudBUIS.Value = (int)training.BUIS;
                    nudMan.Value = (int)training.Men;
                    nudParticipant.Value = (int)training.Participant;
                    nudUIS.Value = (int)training.UIS;
                    nudWoman.Value = (int)training.Women;
                    dtpDate.Value = training.Date;

                    tabControl1.SelectedTab = tabPageTraining;
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsRep)
                tabControl1.SelectedTab = tabPageViewTraining;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            if (regID > 0)
            {
                var result = DBClass.Trainings.Where(wh => wh.RegionID == regID);
                if (chbDate.Checked && chbFromDate.Checked)
                {
                    result = result.Where(wh => wh.Date >= dtpFrom.Value.Date && wh.Date <= dtpToDate.Value.Date);
                }
                else if (chbDate.Checked && !chbFromDate.Checked)
                {
                    result = result.Where(wh => wh.Date == dtpFrom.Value.Date);
                }

                dgvTrainings.DataSource = result.Select(se => new
                {
                    RegName = DBClass.Regions.Where(wh => wh.ID == se.RegionID).Select(sel => sel.Name).FirstOrDefault(),
                    TrName = se.Name,
                    TrDate = se.Date,
                    TrDayCount = se.DayCount,
                    TrPlace = se.Place,
                    ResponsiblePerson = se.ResponsiblePerson,
                    Objective = se.Objective,
                    Audience = se.Audience,
                    Participant = se.Participant,
                    Man = se.Men,
                    Woman = se.Women,
                    UIScount = se.UIS,
                    BUIScount = se.BUIS,
                    Activity = se.Activity
                });
            }
            else
            {
                var result = DBClass.Trainings.Where(wh => wh.RegionID > 0);
                if (chbDate.Checked && chbFromDate.Checked)
                {
                    result = result.Where(wh => wh.Date >= dtpFrom.Value.Date && wh.Date <= dtpToDate.Value.Date);
                }
                else if (chbDate.Checked && !chbFromDate.Checked)
                {
                    result = result.Where(wh => wh.Date == dtpFrom.Value.Date);
                }

                dgvTrainings.DataSource = result.Select(se => new
                {
                    RegName = DBClass.Regions.Where(wh => wh.ID == se.RegionID).Select(sel => sel.Name).FirstOrDefault(),
                    TrName = se.Name,
                    TrDate = se.Date,
                    TrDayCount = se.DayCount,
                    TrPlace = se.Place,
                    ResponsiblePerson = se.ResponsiblePerson,
                    Objective = se.Objective,
                    Audience = se.Audience,
                    Participant = se.Participant,
                    Man = se.Men,
                    Woman = se.Women,
                    UIScount = se.UIS,
                    BUIScount = se.BUIS,
                    Activity = se.Activity
                });
            }

            if (InformationClass.Lang)
            {
                dgvTrainings.Columns["RegName"].HeaderText = "Район";
                dgvTrainings.Columns["TrName"].HeaderText = "Название тренинга";
                dgvTrainings.Columns["TrDate"].HeaderText = "Дата";
                dgvTrainings.Columns["TrDayCount"].HeaderText = "Кол-во дней";
                dgvTrainings.Columns["TrPlace"].HeaderText = "Место проведения";
                dgvTrainings.Columns["ResponsiblePerson"].HeaderText = "Ответственные";
                dgvTrainings.Columns["Objective"].HeaderText = "Цель";
                dgvTrainings.Columns["Audience"].HeaderText = "Требуемая аудитория";
                dgvTrainings.Columns["Participant"].HeaderText = "Кол-во учасников";
                dgvTrainings.Columns["Man"].HeaderText = "Мужчин";
                dgvTrainings.Columns["Woman"].HeaderText = "Женщин";
                dgvTrainings.Columns["UIScount"].HeaderText = "из УИС";
                dgvTrainings.Columns["BUIScount"].HeaderText = "из БУИС";
                dgvTrainings.Columns["Activity"].HeaderText = "Последующая деятельность";
            }
            else
            {
                dgvTrainings.Columns["RegName"].HeaderText = "Туман";
                dgvTrainings.Columns["TrName"].HeaderText = "Тренинг номи";
                dgvTrainings.Columns["TrDate"].HeaderText = "Сони";
                dgvTrainings.Columns["TrDayCount"].HeaderText = "Кунлар сони";
                dgvTrainings.Columns["TrPlace"].HeaderText = "Ўтказиш жойи";
                dgvTrainings.Columns["ResponsiblePerson"].HeaderText = "Жавобгар шахслар";
                dgvTrainings.Columns["Objective"].HeaderText = "Мақсади";
                dgvTrainings.Columns["Audience"].HeaderText = "Зарур аудитория";
                dgvTrainings.Columns["Participant"].HeaderText = "Иштирокчилар сони";
                dgvTrainings.Columns["Man"].HeaderText = "Эркаклар";
                dgvTrainings.Columns["Woman"].HeaderText = "Аёллар";
                dgvTrainings.Columns["UIScount"].HeaderText = "ИТБдан";
                dgvTrainings.Columns["BUIScount"].HeaderText = "ИТҲБдан";
                dgvTrainings.Columns["Activity"].HeaderText = "Кейинги фаолият";
            }
        }



        private void tsbDelete_Click(object sender, EventArgs e)
        {
            if (dgvTrainings.RowCount > 0 && dgvTrainings.CurrentRow != null)
            {
                string msg = InformationClass.Lang ? "Вы действительно хотите удалить тренинг?" : "Сиз ҳақиқатдан ҳам тренингни олиб ташламоқчимисиз?";

                if (MessageBox.Show(msg, msgClass.msgAchtung, MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    DateTime trDate = (DateTime)dgvTrainings["TrDate", dgvTrainings.CurrentRow.Index].Value;
                    training = DBClass.Trainings.Where(wh => wh.Date == trDate && wh.RegionID == regID).SingleOrDefault();

                    if (training != null)
                    {
                        DBClass.Trainings.DeleteOnSubmit(training);
                        DBClass.RESPContext.SubmitChanges();
                        training = null;
                        buttonShow_Click(sender, e);
                    }
                }
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;
        Workbooks excelappworkbooks;

        private void tsbReport_Click(object sender, EventArgs e)
        {
            if (dgvTrainings.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();

                excelworksheet.Select(1);
                excelapp.Visible = true;
            }
        }

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r22.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\r22uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";

            for (int i = 0; i < dgvTrainings.Rows.Count; i++)
            {
                for (int j = 0; j < dgvTrainings.Columns.Count; j++)
                {
                    excelworksheet.Cells[i + 7, dgvTrainings.Columns[j].DisplayIndex + 3] = dgvTrainings[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + 7, dgvTrainings.Columns[j].DisplayIndex + 3]);
                }

                excelworksheet.Cells[i + 7, 2] = i + 1;
            }
            excelworksheet.Columns.AutoFit();
            excelworksheet.Rows.AutoFit();
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonTrCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void chbDate_CheckedChanged(object sender, EventArgs e)
        {
            label18.Visible = chbFromDate.Enabled = dtpToDate.Enabled = chbDate.Checked;
        }

        private void butPrint_Click(object sender, EventArgs e)
        {
            if (dgvTrainings.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvTrainings);
        }
    }
}
